package priv.utrix.micro.converter;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.util.StringUtils;
import priv.utrix.micro.dto.SecurityUserDto;

import java.util.Collection;
import java.util.Map;

import static cn.hutool.core.map.MapUtil.*;
import static priv.utrix.micro.constant.UserMapKeyConstants.AUTHORITY_CODE_LIST;
import static priv.utrix.micro.constant.UserMapKeyConstants.USER_ID;

/**
 * 自定义token解析器，从jwt token中解析用户信息
 *
 * @author utrix
 * @date 2020/11/23
 */
public class CustomUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    /**
     * 重写抽取用户数据方法
     * @author javadaily
     * @date 2020/11/18 10:56
     * @param map 用户认证信息
     * @return Authentication
     */
    @Override
    public Authentication extractAuthentication(Map<String, ?> map) {
        if (map.containsKey(USERNAME)) {
            Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
            String username = getStr(map, USERNAME);
            Long id = getLong(map, USER_ID);
            String[] authorityCodeList = get(map, AUTHORITY_CODE_LIST, String[].class);
            SecurityUserDto user = new SecurityUserDto(username,"N/A", authorities, id, authorityCodeList);
            return new UsernamePasswordAuthenticationToken(user, "N/A", authorities);
        }
        return null;
    }

    private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        Object authorities = map.get(AUTHORITIES);
        if (authorities instanceof String) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
        }
        if (authorities instanceof Collection) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
                    .collectionToCommaDelimitedString((Collection<?>) authorities));
        }
        throw new IllegalArgumentException("Authorities must be either a String or a Collection");
    }

}